@workover/mcp 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -34,6 +34,33 @@ The server authenticates with the token from `workover login` and is **read + pr
34
34
 
35
35
  The API endpoint comes from your `workover login` (defaults to `https://api.workover.dev`).
36
36
 
37
+ ## Usage data
38
+
39
+ To learn which tools agents actually reach for and where they fail, this server records **one event
40
+ per tool call**:
41
+
42
+ - the tool name (`workover_read_doc`, `workover_search_docs`, ...)
43
+ - how long the call took, and whether it succeeded
44
+ - which MCP client called it (Claude Code, Cursor, ...) and its version
45
+
46
+ **It never sends your documents.** Not the arguments you pass, not the results you get back, not
47
+ your file paths. `workover_propose_edits` takes an entire document as an argument and that argument
48
+ is never read by this. What is sent is the shape of the call, not its contents.
49
+
50
+ It is sent **to Workover's own API**, using the token you already signed in with, and is recorded
51
+ against your Workover account. The server ships no analytics credential of its own and talks to no
52
+ third party directly.
53
+
54
+ Turn it off with either of:
55
+
56
+ ```bash
57
+ export DO_NOT_TRACK=1 # the cross-tool standard; disables it here too
58
+ export WORKOVER_TELEMETRY=0 # this package only
59
+ ```
60
+
61
+ Nothing is sent when you are not signed in, and nothing is sent from a local development setup or
62
+ from any API host other than Workover's own.
63
+
37
64
  ---
38
65
 
39
66
  © ScaleMath. All rights reserved.
package/index.mjs CHANGED
@@ -13,6 +13,11 @@ import { readFileSync } from 'fs';
13
13
  import { homedir } from 'os';
14
14
  import { join } from 'path';
15
15
  import { makeApi, makeDispatch, validAuth } from './lib.mjs';
16
+ import {
17
+ buildToolCallEvent,
18
+ sendEvent,
19
+ telemetryEnabled,
20
+ } from './telemetry.mjs';
16
21
 
17
22
  function loadAuth() {
18
23
  try {
@@ -117,6 +122,9 @@ const TOOLS = [
117
122
  },
118
123
  ];
119
124
 
125
+ const telemetry = telemetryEnabled(process.env, { auth });
126
+ const VERSION = '0.2.0';
127
+
120
128
  const server = new Server(
121
129
  { name: 'workover', version: '0.1.0' },
122
130
  { capabilities: { tools: {} } },
@@ -124,9 +132,52 @@ const server = new Server(
124
132
 
125
133
  server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: TOOLS }));
126
134
 
135
+ /**
136
+ * Which tools agents reach for, and where they fail.
137
+ *
138
+ * Wrapped HERE because every tool call arrives through this one handler, so instrumenting it cannot
139
+ * miss a tool the way per-tool instrumentation would as soon as somebody adds the next one.
140
+ *
141
+ * `args` is in scope and is deliberately never touched. For this server the arguments ARE the
142
+ * customer's documents - `workover_propose_edits` takes the complete revised document - so the
143
+ * event carries the tool NAME, how long it took and whether it worked, and nothing else. See
144
+ * telemetry.mjs.
145
+ *
146
+ * The result is returned before the event is sent, and the send is never awaited: an MCP server
147
+ * that made an agent wait on an analytics endpoint would be a worse product than one with no
148
+ * analytics at all.
149
+ */
127
150
  server.setRequestHandler(CallToolRequestSchema, async (req) => {
128
151
  const { name, arguments: args = {} } = req.params;
129
- return dispatch(name, args);
152
+ if (!telemetry) return dispatch(name, args);
153
+
154
+ const startedAt = Date.now();
155
+ try {
156
+ const result = await dispatch(name, args);
157
+ report(name, startedAt, !result?.isError, result?.isError ? 'tool_error' : null);
158
+ return result;
159
+ } catch (error) {
160
+ // Reported, then rethrown untouched. A crash in our dispatch must still reach the client as a
161
+ // crash; swallowing it to keep the analytics tidy would hide the bug.
162
+ report(name, startedAt, false, 'exception');
163
+ throw error;
164
+ }
130
165
  });
131
166
 
167
+ function report(tool, startedAt, ok, errorKind) {
168
+ void sendEvent(
169
+ buildToolCallEvent({
170
+ tool,
171
+ durationMs: Date.now() - startedAt,
172
+ ok,
173
+ errorKind,
174
+ version: VERSION,
175
+ client: server.getClientVersion?.() ?? null,
176
+ }),
177
+ // The API attributes the event to whoever this token belongs to. Nothing here nominates an
178
+ // identity, because a client that could would be a client that could claim somebody else's.
179
+ { auth },
180
+ );
181
+ }
182
+
132
183
  await server.connect(new StdioServerTransport());
package/lib.mjs ADDED
@@ -0,0 +1,222 @@
1
+ // Pure/injectable helpers for the Workover MCP server, split out so they can be unit-tested without
2
+ // importing index.mjs (which starts the stdio server on load). index.mjs wires the real fetch/auth/fs
3
+ // into makeApi + makeDispatch; tests inject stubs.
4
+
5
+ /** Flatten HTML to readable plain text: drop tags + named entities, collapse whitespace. */
6
+ export const stripHtml = (h) =>
7
+ (h || '')
8
+ .replace(/<[^>]+>/g, ' ')
9
+ .replace(/&[a-z]+;/g, ' ')
10
+ .replace(/\s+/g, ' ')
11
+ .trim();
12
+
13
+ /** Wrap a string as a successful MCP tool result. */
14
+ export const text = (t) => ({ content: [{ type: 'text', text: t }] });
15
+
16
+ /** Wrap a string as an MCP tool error result (isError: true → the client shows it as a failure). */
17
+ export const err = (t) => ({ content: [{ type: 'text', text: t }], isError: true });
18
+
19
+ /**
20
+ * Whether a stored config is usable — the sign-in gate.
21
+ *
22
+ * Both a token and an api base, and THE BASE MUST BE HTTPS. That last part is a real constraint
23
+ * rather than tidiness: every request this server makes sends the bearer token to whatever host the
24
+ * config file names, so the file is an exfiltration primitive for anything that can write it. It is
25
+ * a modest one — anything able to write that file can already read the token out of it — but
26
+ * sending the credential in clear text to an arbitrary host is a step worse than merely having it
27
+ * stolen locally, and it costs nothing to refuse.
28
+ *
29
+ * This does NOT satisfy CodeQL's `js/file-access-to-http`, and it was written believing it would.
30
+ * Validating a value and then still using it leaves the dataflow exactly as it was - file to
31
+ * network - so the alert stayed open, correctly. Telemetry resolves its address from a fixed table
32
+ * instead (see `telemetry.mjs`), which it can afford to do because it is optional. A tool call
33
+ * cannot: it MUST reach whatever API the user signed in to, so here the honest answer is a
34
+ * constraint on the value rather than a replacement of it.
35
+ *
36
+ * Which is worth keeping regardless of what any checker thinks of it: the token travels to
37
+ * whatever host this file names, and clear text to an arbitrary host is a step worse than a
38
+ * credential stolen locally.
39
+ *
40
+ * `http://localhost` and `127.0.0.1` are allowed, because local development is the one case where
41
+ * there is no network to sniff and requiring a certificate would just make people turn the check
42
+ * off.
43
+ */
44
+ export const validAuth = (cfg) => {
45
+ if (!cfg?.token || !cfg?.api) return null;
46
+ return isSafeApiBase(cfg.api) ? cfg : null;
47
+ };
48
+
49
+ /** An https origin, or a loopback address during local development. */
50
+ export const isSafeApiBase = (api) => {
51
+ let url;
52
+ try {
53
+ url = new URL(String(api));
54
+ } catch {
55
+ return false;
56
+ }
57
+ if (url.protocol === 'https:') return true;
58
+ return (
59
+ url.protocol === 'http:' &&
60
+ (url.hostname === 'localhost' ||
61
+ url.hostname === '127.0.0.1' ||
62
+ url.hostname === '[::1]' ||
63
+ url.hostname === '::1')
64
+ );
65
+ };
66
+
67
+ /**
68
+ * Coerce a tool-supplied row id, or null if it isn't one.
69
+ *
70
+ * Agents pass whatever they have to hand: the `#12345` shown by workover_search_docs, or the
71
+ * publicId handle out of a document URL. `Number(...)` turned every one of those into `NaN`, which
72
+ * we then sent as a literal `/project/doc/NaN` — the API answered 500 and paged on-call (the same
73
+ * class of bug as Better Stack incident 995716123). Reject it here, with a message that says what
74
+ * to pass instead, rather than making the server decide.
75
+ */
76
+ export const rowId = (v) => {
77
+ const s = String(v ?? '')
78
+ .trim()
79
+ .replace(/^#/, '');
80
+ return /^\d+$/.test(s) ? Number(s) : null;
81
+ };
82
+
83
+ /** The error shown when a tool is handed something that isn't a numeric id. */
84
+ export const badIdErr = (kind, got) =>
85
+ err(
86
+ `"${got}" isn't a ${kind} id. Pass the numeric id (e.g. 12345) — the one workover_search_docs prints as "#12345" or workover_list_projects as "#7". A handle from a document URL won't work here.`,
87
+ );
88
+
89
+ /** Map an image file extension to its mime type (defaults to png). */
90
+ export const mimeForExt = (ext) => {
91
+ const e = String(ext || '').toLowerCase();
92
+ if (e === 'jpg' || e === 'jpeg') return 'image/jpeg';
93
+ if (e === 'webp') return 'image/webp';
94
+ return 'image/png';
95
+ };
96
+
97
+ /**
98
+ * Build the authenticated JSON API caller. `fetchImpl` is injectable for tests. The status→message
99
+ * mapping is the contract the tools rely on (401/403 are friendly, other non-2xx is generic).
100
+ */
101
+ export function makeApi({ auth, fetchImpl = fetch }) {
102
+ async function api(path, init) {
103
+ const res = await fetchImpl(`${auth.api}${path}`, {
104
+ ...init,
105
+ headers: { authorization: `Bearer ${auth.token}`, ...(init?.headers || {}) },
106
+ });
107
+ if (res.status === 401)
108
+ throw new Error('Your Workover login expired or was revoked. Run `workover login`.');
109
+ if (res.status === 403) throw new Error('This token isn’t allowed to do that.');
110
+ if (!res.ok) throw new Error(`Workover API error (${res.status}).`);
111
+ return res.json();
112
+ }
113
+ const apiPost = (path, body) =>
114
+ api(path, {
115
+ method: 'POST',
116
+ headers: { 'content-type': 'application/json' },
117
+ body: JSON.stringify(body),
118
+ });
119
+ return { api, apiPost };
120
+ }
121
+
122
+ /**
123
+ * Build the CallTool dispatcher. Returns `dispatch(name, args)` → an MCP result. Not-signed-in
124
+ * short-circuits before any request; unknown tools and thrown errors become `err(...)`. `readFile`
125
+ * and `fetchImpl` are injected so the upload path is testable without touching the disk/network.
126
+ */
127
+ export function makeDispatch({ auth, api, apiPost, fetchImpl = fetch, readFile }) {
128
+ return async function dispatch(name, args = {}) {
129
+ if (!auth)
130
+ return err('Not signed in to Workover. Run `workover login` in your terminal first.');
131
+ try {
132
+ if (name === 'workover_search_docs') {
133
+ const { results = [] } = await api(
134
+ `/search/documents?q=${encodeURIComponent(String(args.query || ''))}&limit=10`,
135
+ );
136
+ if (!results.length) return text('No matching documents.');
137
+ return text(
138
+ results
139
+ .map(
140
+ (r) =>
141
+ `#${r.id} — ${r.title || 'Untitled'}${r.snippet ? `\n ${stripHtml(r.snippet)}` : ''}`,
142
+ )
143
+ .join('\n'),
144
+ );
145
+ }
146
+ if (name === 'workover_read_doc') {
147
+ const docId = rowId(args.docId);
148
+ if (docId === null) return badIdErr('document', args.docId);
149
+ const d = await api(`/project/doc/${docId}`);
150
+ if (!d || !d.id) return err(`Document ${docId} not found (or no access).`);
151
+ const body = d.bodyText || stripHtml(d.content) || '(empty document)';
152
+ return text(`# ${d.title || 'Untitled'} (id ${d.id})\n\n${body}`);
153
+ }
154
+ if (name === 'workover_list_projects') {
155
+ const projects = await api('/project');
156
+ const list = Array.isArray(projects) ? projects : projects?.projects || [];
157
+ if (!list.length) return text('No projects.');
158
+ return text(list.map((p) => `#${p.id} — ${p.name || p.title || 'Project'}`).join('\n'));
159
+ }
160
+ if (name === 'workover_create_doc') {
161
+ const title = String(args.title || '').trim();
162
+ const md = String(args.markdown || '').trim();
163
+ if (!title || !md) return err('Provide both a `title` and the body as `markdown`.');
164
+ const projectId = rowId(args.projectId);
165
+ if (projectId === null) return badIdErr('project', args.projectId);
166
+ const doc = await apiPost(`/project/${projectId}/documents`, { title });
167
+ if (!doc?.id) return err('Could not create the document.');
168
+ const proposal = await apiPost(`/project/doc/${doc.id}/propose`, {
169
+ markdown: md,
170
+ source: 'Claude Code',
171
+ });
172
+ return text(
173
+ `Created "${title}" (document #${doc.id}) and added the content as suggestions to review.${proposal?.documentUrl ? `\n${proposal.documentUrl}` : ''}\n\nOpen it in Workover to accept or reject the changes — nothing is published.`,
174
+ );
175
+ }
176
+ if (name === 'workover_upload_image') {
177
+ const p = String(args.path || '');
178
+ if (!p) return err('Provide the local `path` to the image file.');
179
+ const docId = rowId(args.docId);
180
+ if (docId === null) return badIdErr('document', args.docId);
181
+ let buf;
182
+ try {
183
+ buf = readFile(p);
184
+ } catch {
185
+ return err(`Couldn't read an image at ${p}.`);
186
+ }
187
+ const ext = (p.split('.').pop() || 'png').toLowerCase();
188
+ const mime = mimeForExt(ext);
189
+ const form = new FormData();
190
+ form.append('file', new Blob([buf], { type: mime }), p.split('/').pop() || `image.${ext}`);
191
+ if (args.alt) form.append('alt', String(args.alt));
192
+ const res = await fetchImpl(`${auth.api}/project/doc/${docId}/media`, {
193
+ method: 'POST',
194
+ headers: { authorization: `Bearer ${auth.token}` },
195
+ body: form,
196
+ });
197
+ if (!res.ok) return err(`Upload failed (${res.status}).`);
198
+ const { url } = await res.json();
199
+ return text(
200
+ `Uploaded. Reference it in the document markdown:\n\n![${args.alt || 'screenshot'}](${url})`,
201
+ );
202
+ }
203
+ if (name === 'workover_propose_edit') {
204
+ const md = String(args.markdown || '').trim();
205
+ if (!md) return err('Provide the full revised document as `markdown`.');
206
+ const docId = rowId(args.docId);
207
+ if (docId === null) return badIdErr('document', args.docId);
208
+ const res = await apiPost(`/project/doc/${docId}/propose`, {
209
+ markdown: md,
210
+ note: args.note ? String(args.note) : undefined,
211
+ source: 'Claude Code',
212
+ });
213
+ return text(
214
+ `Proposed your changes to document #${docId}. They'll appear as suggestions to accept or reject when the document is open in Workover${res?.documentUrl ? `:\n${res.documentUrl}` : '.'}\n\nNothing is published until the person reviews and accepts.`,
215
+ );
216
+ }
217
+ return err(`Unknown tool: ${name}`);
218
+ } catch (e) {
219
+ return err(e?.message || 'Something went wrong.');
220
+ }
221
+ };
222
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@workover/mcp",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Workover MCP server — let Claude Code and other MCP clients read and cowork on your Workover documents.",
5
5
  "license": "UNLICENSED",
6
6
  "author": "ScaleMath",
@@ -21,6 +21,8 @@
21
21
  },
22
22
  "files": [
23
23
  "index.mjs",
24
+ "lib.mjs",
25
+ "telemetry.mjs",
24
26
  "README.md"
25
27
  ],
26
28
  "engines": {
package/telemetry.mjs ADDED
@@ -0,0 +1,194 @@
1
+ /**
2
+ * Which tools agents actually reach for, and where they fail.
3
+ *
4
+ * This is the question worth answering about an MCP server: we ship tools into other people's
5
+ * agents and have no idea which ones get used, which get called with bad arguments, or which are
6
+ * slow enough that an agent gives up.
7
+ *
8
+ * WHAT IT NEVER SENDS, AND WHY THAT IS NOT NEGOTIABLE
9
+ *
10
+ * Not the arguments. Not the results. PostHog's MCP analytics describes capturing "every tool call,
11
+ * argument and result", and for THIS server that would mean shipping customers' documents off their
12
+ * own laptops: `workover_propose_edits` takes the complete revised document as an argument, and
13
+ * every read tool returns document contents. Nobody installing an MCP server expects it to send
14
+ * their writing to the vendor's analytics, and "we captured the arguments" is not a defence.
15
+ *
16
+ * So: the tool NAME, how long it took, whether it worked, and what kind of failure it was.
17
+ *
18
+ * IT REPORTS THROUGH THE WORKOVER API, NOT STRAIGHT TO POSTHOG
19
+ *
20
+ * The first version embedded a PostHog project token in the published package. The reasoning was
21
+ * that these tokens are write-only and documented as safe in public clients, which is true - it is
22
+ * the same token a web app exposes in its bundle. It was still the wrong call for two reasons that
23
+ * have nothing to do with how dangerous the token is:
24
+ *
25
+ * A credential in a published tarball is a credential you cannot rotate. Changing it means every
26
+ * installed copy keeps using the old one until each user upgrades, so the thing that makes
27
+ * rotation possible - being able to stop honouring the old value - is exactly what you lose. It
28
+ * also trips secret scanning on every push, and an alert that is always there is an alert nobody
29
+ * reads.
30
+ *
31
+ * It threw away the identity. A hash of the token is a pseudonym: it groups one installation's
32
+ * calls together and tells you nothing else. Sent through the API, the server already knows who
33
+ * the token belongs to, so MCP usage lands on the same person and workspace as everything else -
34
+ * which is what makes "this workspace uses the MCP server heavily and drafts nothing" a question
35
+ * anyone can ask.
36
+ *
37
+ * The cost, stated rather than discovered: an unauthenticated install now reports NOTHING, because
38
+ * there is no token to authenticate the relay with and no API base configured to send it to. That
39
+ * loses the "somebody installed it and never signed in" signal. It is a thin signal - an
40
+ * unauthenticated server cannot complete a single tool call anyway, since every tool goes through
41
+ * the API - and the alternative was a public unauthenticated write endpoint into our own analytics,
42
+ * which is the same junk-event exposure as the embedded token with none of the benefit.
43
+ *
44
+ * WHERE IT MAY SEND, AND WHY THAT IS A FIXED LIST
45
+ *
46
+ * Only to a host in `KNOWN_API_BASES`, and the URL is taken FROM that table rather than from the
47
+ * config file - the file's host is only ever used as a lookup key. So the address this posts to is
48
+ * a constant in this source file, and nothing a config file says can change it.
49
+ *
50
+ * That is stricter than the tool calls in `lib.mjs`, deliberately. A tool call must reach whatever
51
+ * API the user signed in to or the product does not work; telemetry is optional, so it can afford
52
+ * to refuse anything it does not already recognise. Local development therefore reports nothing,
53
+ * which is also what we want - it keeps our own machines out of "which clients use which tools".
54
+ *
55
+ * CodeQL found the previous version as `js/file-access-to-http`. The first attempt at a fix only
56
+ * validated the file's value (https, or loopback) and still built the URL from it, which hardened
57
+ * the behaviour without changing the dataflow at all - the alert stayed open, correctly.
58
+ *
59
+ * IT RUNS ON SOMEONE ELSE'S MACHINE
60
+ *
61
+ * Unlike the API, this is a published npm package executing on a customer's laptop. Telemetry that
62
+ * is on by default without disclosure is a thing done TO people, so: `DO_NOT_TRACK` is honoured
63
+ * (the cross-tool standard), `WORKOVER_TELEMETRY=0` turns it off explicitly, and the README says
64
+ * what is collected before anyone installs it.
65
+ */
66
+
67
+ export const TOOL_CALL_EVENT = 'mcp_tool_call';
68
+
69
+ /**
70
+ * Every host telemetry may be sent to, and the exact base URL used for each.
71
+ *
72
+ * The VALUE is what gets used, never the key and never the config file's own string. A host we do
73
+ * not recognise - a fork, a self-hosted API, localhost - reports nothing rather than being trusted
74
+ * with a bearer token.
75
+ */
76
+ const KNOWN_API_BASES = {
77
+ 'api.workover.io': 'https://api.workover.io',
78
+ 'api.workover.dev': 'https://api.workover.dev',
79
+ };
80
+
81
+ /**
82
+ * The base URL to report to, or null for "do not report".
83
+ *
84
+ * Returns a constant from the table above. The configured value is parsed only to read its
85
+ * hostname, which is used as a lookup key and then discarded.
86
+ */
87
+ export function telemetryBaseFor(api) {
88
+ let hostname;
89
+ try {
90
+ hostname = new URL(String(api)).hostname;
91
+ } catch {
92
+ return null;
93
+ }
94
+ return Object.prototype.hasOwnProperty.call(KNOWN_API_BASES, hostname)
95
+ ? KNOWN_API_BASES[hostname]
96
+ : null;
97
+ }
98
+
99
+ /**
100
+ * Whether to send anything at all.
101
+ *
102
+ * Opt-OUT rather than opt-in, which is the choice worth being honest about: opt-in telemetry from a
103
+ * CLI is telemetry nobody enables, so the data would not exist. That is only defensible because
104
+ * what is sent carries no content, and because turning it off is one standard environment variable
105
+ * that many people already set globally.
106
+ *
107
+ * Signed in is now a precondition rather than a property of the event. There is nowhere to send an
108
+ * anonymous one: the API base lives in the same stored config as the token.
109
+ */
110
+ export function telemetryEnabled(env = process.env, { auth = null } = {}) {
111
+ if (env.DO_NOT_TRACK === '1' || env.DO_NOT_TRACK === 'true') return false;
112
+ if (env.WORKOVER_TELEMETRY === '0' || env.WORKOVER_TELEMETRY === 'false') {
113
+ return false;
114
+ }
115
+ return Boolean(auth?.token && telemetryBaseFor(auth?.api));
116
+ }
117
+
118
+ /**
119
+ * One tool call, as an event.
120
+ *
121
+ * `ok` is separate from `errorKind` on purpose: a tool that returned `isError` is a DIFFERENT thing
122
+ * from a tool that threw, and collapsing them would hide the case where our own dispatch crashes
123
+ * behind the ordinary "no documents matched" answer.
124
+ *
125
+ * No `distinct_id`. The API knows whose token this is and attributes it there - a client that
126
+ * nominated its own identity could claim anybody's, and the server would have no way to tell.
127
+ */
128
+ export function buildToolCallEvent({
129
+ tool,
130
+ durationMs,
131
+ ok,
132
+ errorKind = null,
133
+ version = null,
134
+ client = null,
135
+ }) {
136
+ return {
137
+ event: TOOL_CALL_EVENT,
138
+ properties: {
139
+ mcp_tool: tool,
140
+ mcp_duration_ms: Math.max(0, Math.round(durationMs)),
141
+ mcp_ok: Boolean(ok),
142
+ ...(errorKind ? { mcp_error_kind: errorKind } : {}),
143
+ ...(version ? { mcp_server_version: version } : {}),
144
+ // Which agent is calling: Claude Code, Cursor, Codex. The whole point of the question is
145
+ // which clients use which tools, and the MCP handshake tells us without asking the user.
146
+ ...(client?.name ? { mcp_client: client.name } : {}),
147
+ ...(client?.version ? { mcp_client_version: client.version } : {}),
148
+ },
149
+ };
150
+ }
151
+
152
+ /**
153
+ * Send one event, and never let it matter.
154
+ *
155
+ * Fire-and-forget with a short timeout, every failure swallowed. An MCP server that stalls or
156
+ * crashes because an analytics endpoint is slow would be a straightforwardly worse product than one
157
+ * with no analytics at all - and this one runs on somebody's laptop while they are trying to work.
158
+ *
159
+ * Nothing is ever written to stdout. This process speaks the MCP protocol over stdio, so a stray
160
+ * `console.log` corrupts the stream and breaks the client - which is a much easier mistake to make
161
+ * than it looks.
162
+ */
163
+ export async function sendEvent(event, { auth, fetchImpl } = {}) {
164
+ // The base comes from the table, not from the file. Re-resolved here rather than trusted from
165
+ // the caller: a guard that only exists somewhere else is a guard the next caller will not have.
166
+ const base = auth?.token ? telemetryBaseFor(auth.api) : null;
167
+ if (!base) return false;
168
+
169
+ const doFetch = fetchImpl ?? globalThis.fetch;
170
+ if (typeof doFetch !== 'function') return false;
171
+
172
+ const controller = new AbortController();
173
+ const timer = setTimeout(() => controller.abort(), 2000);
174
+
175
+ try {
176
+ await doFetch(`${base}/mcp/telemetry`, {
177
+ method: 'POST',
178
+ headers: {
179
+ 'content-type': 'application/json',
180
+ authorization: `Bearer ${auth.token}`,
181
+ },
182
+ body: JSON.stringify({
183
+ event: event.event,
184
+ properties: event.properties,
185
+ }),
186
+ signal: controller.signal,
187
+ });
188
+ return true;
189
+ } catch {
190
+ return false;
191
+ } finally {
192
+ clearTimeout(timer);
193
+ }
194
+ }